package com.spiro.gis.tiledownload;

import java.util.concurrent.BlockingQueue;

/**
 * @Author: Shaoping Huang
 * @Description:
 * @Date: 1/14/2018
 */
public class TileCoordinateGenerator {

    private final int maxLevel;
    private final boolean recursive;
    private final BlockingQueue<TileCoordinate> queue;
    private long generateCount = 0;

    public TileCoordinateGenerator(int maxLevel, boolean recursive, BlockingQueue<TileCoordinate> queue) {
        this.maxLevel = maxLevel;
        this.recursive = recursive;
        this.queue = queue;
    }

    public void generate() {
        if (maxLevel < 0) {
            throw new IllegalArgumentException("maxLevel should not less than zero.");
        }

        if (queue == null) {
            throw new IllegalArgumentException("queue should not be null.");
        }

        try {
            if (recursive) {
                int levelNum = maxLevel + 1;
                for (int z = 0; z < levelNum; z++) {
                    generateLevelTile(z);
                }
            } else {
                generateLevelTile(maxLevel);
            }

        } catch (InterruptedException e) {
        }

        System.out.println("Generate completely, generateCount=" + generateCount);
    }

    public void generateLevelTile(final int level) throws InterruptedException {
        int z = level;
        int rowNum = (int) Math.pow(2, z);
        int colNum = rowNum;
        for (int x = 0; x < rowNum; x++) {
            for (int y = 0; y < colNum; y++) {
                TileCoordinate coordinate = new TileCoordinate(z, x, y);
                this.queue.put(coordinate);
                generateCount++;
            }
        }
    }

    public long getGenerateCount() {
        return generateCount;
    }
}
